package dnl.ui;

import java.awt.Component;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileChooserUtils {

	public static enum DefaultDirPolicy {USER_HOME, APP_DIR};
	
	private static File lastSelectedDir;
	static {
		setDefaultDirPolicy(DefaultDirPolicy.USER_HOME);
	}
	
	public static void setDefaultDirPolicy(DefaultDirPolicy defaultDirPolicy){
		switch (defaultDirPolicy) {
		case USER_HOME:
			lastSelectedDir = new File(System.getProperty("user.home"));
			break;
		case APP_DIR:
			lastSelectedDir = new File(System.getProperty("."));
			break;
		}
	}

	public static void setLastSelectedDir(File f){
		lastSelectedDir = f;
	}
	
	public static File saveAs(Component parent, String initialFileName) {
		JFileChooser fc = new JFileChooser();
		if (initialFileName != null) {
			int ind = initialFileName.lastIndexOf('.');
			if (ind > 1) {
				String ext = initialFileName.substring(ind + 1);
				if(ext == null || ext.isEmpty()){
					System.out.println();
				}
				FileNameExtensionFilter filter = new FileNameExtensionFilter(ext, ext);
				fc.setFileFilter(filter);
			}
			fc.setSelectedFile(new File(lastSelectedDir, initialFileName));
		}
		fc.setCurrentDirectory(lastSelectedDir);
		fc.setDialogTitle("Save As");
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int returnVal = fc.showOpenDialog(parent);

		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File selectedFile = fc.getSelectedFile();
			lastSelectedDir = selectedFile.getParentFile();
			return selectedFile;
		}
		return null;
	}

	public static File selectFileForSaving(Component parent) {
		return selectFileImpl(parent, false, JFileChooser.SAVE_DIALOG);
	}

	public static File selectFile(Component parent) {
		return selectFileImpl(parent, false, JFileChooser.OPEN_DIALOG);
	}

	public static File selectDirectory(Component parent) {
		return selectFileImpl(parent, true, JFileChooser.OPEN_DIALOG);
	}
	
	private static File selectFileImpl(Component parent, boolean selectDir, int dialogType) {
		JFileChooser fc = new JFileChooser();
		fc.setDialogType(dialogType);
		fc.setCurrentDirectory(lastSelectedDir);
		if(selectDir){
			fc.setDialogTitle("Select Directory");
			fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		}
		else {
			fc.setDialogTitle("Select File");
			fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		}
		int returnVal = fc.showOpenDialog(parent);
		
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File selectedFile = fc.getSelectedFile();
			lastSelectedDir = selectedFile.getParentFile();
			return selectedFile;
		}
		return null;
	}
}
